// main.js
import React, { useState, useEffect } from 'react';
import {
  MenuFoldOutlined, MenuUnfoldOutlined, createFromIconfontCN, BellOutlined, UserOutlined, SettingOutlined, DownOutlined, MenuOutlined
} from '@ant-design/icons';

import { Button, Input, Menu, Select, Tabs, Modal, Badge, Dropdown, Avatar, Space } from 'antd';
import { fetchsync_util } from './shipSRM/util/util.js'
import { useHistory,useLocation } from 'react-router-dom';
import logo from '../img/shipSRM/chlogo.png'
import './mainpage.css'
import Highlighter from 'react-highlight-words';
import { openNotification_util } from './shipSRM/util/util.js';
import useStore from './useStore.js'
import { v4 as uuidv4 } from 'uuid';
const { Search } = Input
import { dropByCacheKey } from 'react-router-cache-route';
import { Menu as RightMenu, Item, contextMenu } from 'react-contexify';
import 'react-contexify/dist/ReactContexify.css';
import Userinfo from './userinfo.js'
import DynamicComponentLoader from './DynamicComponentLoader.js';
import { getRouteConfig } from './routeConfig.js';
var storage = window.localStorage;
const { Option } = Select;

const IconFont = createFromIconfontCN({
  scriptUrl: 'http://111.77.154.58:2233/icon.js',
});
// Define a unique ID for the menu
const MENU_ID = 'menu-id';

const Mainpage = () => {

  const history = useHistory();

  const location = useLocation();

  const [scList, setScLisst] = useState([])

  const [openKeys, setOpenKeys] = useState([])

  const [menuList, setMenuList] = useState([])

  const [menuRightList, setMenuRightList] = useState([])

  // 一级菜单数据
  const [primaryMenuList, setPrimaryMenuList] = useState([])

  // 当前选中的一级菜单
  const [selectedPrimaryMenu, setSelectedPrimaryMenu] = useState('')

  // 当前一级菜单对应的二级菜单
  const [secondaryMenuList, setSecondaryMenuList] = useState([])

  const [searchText, setSearchText] = useState('')

  const [ifxgmm, setIfxgmm] = useState(false)

  const [activetabs, setActivetabs] = useState([])

  const [nowactiveKey, setnowActiveKey] = useState('')

  //鼠标悬浮的key
  const [nowtabkey, setnowtabkey] = useState('')

  // 令牌校验状态
  const [tokenChecking, setTokenChecking] = useState(false)

  // 消息通知数量
  const [notificationCount, setNotificationCount] = useState(0)

  const { collapsed, setcollapsed, nowroute, setnowroute,
    needrefreshsclist, setneedrefreshsclist } = useStore();

  const extractMenuLabel = (label, fallback = '') => {
    if (label === null || label === undefined) {
      return fallback;
    }

    if (typeof label === 'string' || typeof label === 'number') {
      return String(label).trim() || fallback;
    }

    if (Array.isArray(label)) {
      for (const child of label) {
        const text = extractMenuLabel(child, '');
        if (text) {
          return text;
        }
      }
      return fallback;
    }

    if (React.isValidElement(label)) {
      if (typeof label.props?.textToHighlight === 'string') {
        return label.props.textToHighlight.trim() || fallback;
      }

      const childrenArray = React.Children.toArray(label.props?.children);
      for (const child of childrenArray) {
        const text = extractMenuLabel(child, '');
        if (text) {
          return text;
        }
      }
    }

    return fallback;
  };

  const sanitizeMenuItemForDropdown = (item) => {
    if (!item) {
      return null;
    }

    const fallbackKey = item.key !== undefined && item.key !== null
      ? String(item.key)
      : '';

    const sanitizedChildren = Array.isArray(item.children)
      ? item.children.map(child => sanitizeMenuItemForDropdown(child)).filter(Boolean)
      : undefined;

    return {
      key: fallbackKey,
      label: extractMenuLabel(item.label, fallbackKey),
      icon: item.icon,
      children: sanitizedChildren && sanitizedChildren.length > 0 ? sanitizedChildren : undefined,
    };
  };

  // 确保首页页签始终存在的函数
  const ensureHomeTabExists = (currentTabs) => {
    const homeTab = {
      key: '/shipSRM/mainpage',
      title: '首页',
      route: '/shipSRM/mainpage',
      closable: false // 首页不可关闭
    };

    // 检查是否已经存在首页页签
    const homeTabExists = currentTabs.some(tab => tab.route === '/shipSRM/mainpage');
    
    if (!homeTabExists) {
      // 如果不存在，将首页页签添加到第一个位置
      return [homeTab, ...currentTabs];
    } else {
      // 如果存在，确保首页页签在第一个位置
      const homeTabIndex = currentTabs.findIndex(tab => tab.route === '/shipSRM/mainpage');
      if (homeTabIndex !== 0) {
        const newTabs = [...currentTabs];
        const homeTabItem = newTabs.splice(homeTabIndex, 1)[0];
        return [homeTabItem, ...newTabs];
      }
    }
    
    return currentTabs;
  };

  // Function to handle right-click
  const handleContextMenu = (event) => {
    event.preventDefault();
    contextMenu.show({
      id: MENU_ID,
      event: event,
    });
  };

  // JWT令牌管理
  const setToken = (token) => {
    storage.token = token;
    // 设置令牌过期时间（4小时后）
    storage.tokenExpireTime = Date.now() + 4 * 60 * 60 * 1000;
  }

  const getToken = () => {
    return storage.token;
  }

  const isTokenExpired = () => {
    const expireTime = storage.tokenExpireTime;
    if (!expireTime) return true;
    return Date.now() > expireTime;
  }

  const clearToken = () => {
    storage.removeItem('token');
    storage.removeItem('tokenExpireTime');
  }

  // 检查是否有有效的登录状态
  const hasValidLoginData = () => {
    return storage.userid && storage.ygxm && storage.zh;
  }

  // 自动刷新令牌
  const refreshToken = async () => {
    const token = getToken();
    if (!token) return false;

    try {
      const response = await fetch("/admin/sys/refreshToken", {
        method: 'POST',
        mode: 'cors',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        }
      });

      const data = await response.json();
      if (data.success) {
        setToken(data.data.token);
        console.log('令牌刷新成功');
        return true;
      } else {
        console.log('令牌刷新失败:', data.message);
        return false;
      }
    } catch (error) {
      console.error('刷新令牌失败:', error);
      return false;
    }
  }

  // 强制退出到登录页
  const forceLogout = (message = "登录已过期，请重新登录") => {
    clearToken();
    // 清除所有登录相关的存储数据
    storage.removeItem('userid');
    storage.removeItem('ygxm');
    storage.removeItem('zh');
    storage.removeItem('ygbh');
    storage.removeItem('js');
    storage.removeItem('yhlx');
    storage.removeItem('gysbm');
    storage.removeItem('logintime');
    storage.removeItem('nowroute');
    storage.removeItem('nowurl');
    
    openNotification_util(message);
    history.push('/');
  }

  // 检查并处理令牌过期
  const checkTokenExpiration = async () => {
    if (tokenChecking) return true; // 避免重复检查

    setTokenChecking(true);
    
    try {
      // 首先检查是否有基本的登录数据
      if (!hasValidLoginData()) {
        forceLogout("登录信息不完整，请重新登录");
        return false;
      }

      const token = getToken();
      if (!token) {
        forceLogout("未找到访问令牌，请重新登录");
        return false;
      }

      // 检查令牌是否即将过期（提前10分钟刷新）
      const expireTime = storage.tokenExpireTime;
      const now = Date.now();
      const tenMinutes = 10 * 60 * 1000;
      
      if (!expireTime || now > (expireTime - tenMinutes)) {
        console.log('令牌即将过期，尝试刷新...');
        const refreshSuccess = await refreshToken();
        if (!refreshSuccess) {
          forceLogout("令牌刷新失败，请重新登录");
          return false;
        }
      }

      return true;
    } catch (error) {
      console.error('令牌检查失败:', error);
      forceLogout("令牌验证失败，请重新登录");
      return false;
    } finally {
      setTokenChecking(false);
    }
  }

  // 创建带令牌的请求头
  const createAuthHeaders = () => {
    const token = getToken();
    return {
      'Content-Type': 'application/json',
      ...(token && { 'Authorization': `Bearer ${token}` })
    };
  }

  // 拦截器：处理API请求的令牌验证
  const apiRequest = async (url, options = {}) => {
    // 检查令牌是否过期
    const tokenValid = await checkTokenExpiration();
    if (!tokenValid) {
      throw new Error('登录已过期');
    }

    // 添加认证头
    const headers = createAuthHeaders();
    const requestOptions = {
      ...options,
      headers: { ...headers, ...options.headers }
    };

    try {
      const response = await fetch(url, requestOptions);
      const data = await response.json();

      // 检查返回的错误信息
      if (!data.success && data.message) {
        if (data.message.includes('登录已过期') || 
            data.message.includes('令牌已失效') || 
            data.message.includes('未提供访问令牌') ||
            data.message.includes('无效的访问令牌')) {
          
          // 尝试刷新令牌
          const refreshSuccess = await refreshToken();
          if (refreshSuccess) {
            // 重新发送请求
            const newHeaders = createAuthHeaders();
            const newOptions = {
              ...options,
              headers: { ...newHeaders, ...options.headers }
            };
            const retryResponse = await fetch(url, newOptions);
            const retryData = await retryResponse.json();
            
            // 如果重试后仍然失败，强制登出
            if (!retryData.success && retryData.message && 
                (retryData.message.includes('登录已过期') || 
                 retryData.message.includes('令牌已失效'))) {
              forceLogout("登录状态已失效，请重新登录");
              throw new Error('登录已过期');
            }
            
            return retryData;
          } else {
            // 刷新失败，强制登出
            forceLogout("登录状态已失效，请重新登录");
            throw new Error('登录已过期');
          }
        }
      }

      return data;
    } catch (error) {
      if (error.message === '登录已过期') {
        throw error;
      }
      console.error('API请求失败:', error);
      throw error;
    }
  }

  // Function to handle menu item click
  const handleCloseAll = () => {
    console.log(activetabs, "activetabs");
    // 清空所有标签页的缓存，但保留首页
    for (let i = 0; i < activetabs.length; i++) {
      if (activetabs[i].route !== '/shipSRM/mainpage') {
        dropByCacheKey(activetabs[i].key)
      }
    }
    
    // 确保首页页签存在
    const homeOnlyTabs = ensureHomeTabExists([]);
    setActivetabs(homeOnlyTabs);
    setnowroute({ route: '/shipSRM/mainpage', title: '首页' })
    setnowActiveKey('/shipSRM/mainpage')
    tonormal('/shipSRM/mainpage')

    console.log("关闭全部")
  }
  const handleCloseOther = () => {
    // 保留当前选中的页签和首页页签
    const tabsToKeep = activetabs.filter(tab => 
      tab.key === nowtabkey || tab.route === '/shipSRM/mainpage'
    );
    
    // 清除其他页签的缓存
    for (let i = 0; i < activetabs.length; i++) {
      if (activetabs[i].key !== nowtabkey && activetabs[i].route !== '/shipSRM/mainpage') {
        console.log(activetabs[i].key, "activetabs[i].key")
        dropByCacheKey(activetabs[i].key)
      }
    }
    
    // 确保首页页签在第一个位置
    const finalTabs = ensureHomeTabExists(tabsToKeep);
    setActivetabs(finalTabs);
    setnowActiveKey(nowtabkey)
    tonormal(nowtabkey)
    console.log("关闭其他")
  }

  const handleCloseRight = () => {
    let index = activetabs.findIndex(tab => tab.key === nowtabkey)
    setActivetabs([...activetabs.slice(0, index + 1)])
    for (let i = index + 1; i < activetabs.length; i++) {
      console.log(activetabs[i].key, "activetabs[i].key")
      dropByCacheKey(activetabs[i].key)
    }
    setnowActiveKey(nowtabkey)
    tonormal(nowtabkey)
    console.log("关闭右侧")
  }

  const handleClick = async (item, e) => {
    setneedrefreshsclist(uuidv4())
    e.stopPropagation()
    
    try {
      if (item.sfsc != '是') {
        await updateMenuList("是", item.cdbh, item.cdmc)
        await queryMenuList()
        await queryScList() // 刷新收藏列表
      }
      else {
        await updateMenuList("否", item.cdbh, item.cdmc)
        await queryMenuList()
        await queryScList() // 刷新收藏列表
      }
    } catch (error) {
      console.error('更新菜单失败:', error);
    }
  }

  const queryMenuList = async () => {
    try {
      // 使用新的API请求方法
      let rtdata = await apiRequest("/admin/sys/queryMenuList", {
        method: 'POST',
        body: JSON.stringify({ 
          storage: {
            userid: storage.userid,
            ygbh: storage.ygbh
          }
        })
      });

      // 处理一级菜单，在最前面添加首页
      const homeMenu = {
        label: '首页',
        key: 'homepage',
        route: '/shipSRM/mainpage',
        icon: <IconFont type="home" />,
        cdmc: '首页'
      };
      
      const primaryMenus = [
        homeMenu,
        ...rtdata.yjcdList.map(item => ({
          label: item.cdmc,
          key: item.id,
          route: item.cdly,
          icon: <IconFont type={item.cdtb} />,
          cdmc: item.cdmc
        }))
      ];
      setPrimaryMenuList(primaryMenus);

      // 设置默认选中首页
      if (primaryMenus.length > 0 && !selectedPrimaryMenu) {
        setSelectedPrimaryMenu('首页');
      }

      // 处理二级菜单，首先为首页添加收藏菜单
      const itemArray = []
      
      // 添加首页菜单项
      const homeMenuItem = { 
        label: '首页', 
        key: 'homepage', 
        route: '/shipSRM/mainpage', 
        icon: <IconFont type="home" />, 
        theme: 'light',
        children: [] // 收藏菜单将在后面添加
      }
      itemArray.push(homeMenuItem)
      
      // 处理其他一级菜单
      for (let item of rtdata.yjcdList) {
        let itemObj = { label: item.cdmc, key: item.id, route: item.cdly, icon: <IconFont type={item.cdtb} />, theme: 'light' }
        var childrenArray = []
        for (let itemChild of rtdata.ejcdList) {
          if (item.cdmc == itemChild.parent_mc) {
            let itemObj2 = {
              label: <div id={itemChild.id}><Highlighter highlightStyle={{
                backgroundColor: 'yellow', padding: 0,
              }}
                searchWords={[searchText]} autoEscape textToHighlight={itemChild.cdmc} /><div className="icon-button" style={{ position: 'absolute', right: '1vw', top: '0', zIndex: "10", width: '3vw', textAlign: 'center' }}
                  onClick={e => { handleClick(itemChild, e) }}><IconFont
                    type={itemChild.sfsc != '是' ? "shoucang" : "yellowStar"}></IconFont></div>
              </div>, key: itemChild.cdmc, route: itemChild.cdly, theme: 'light', id: itemChild.id, parent_mc: itemChild.parent_mc
            }
            childrenArray.push(itemObj2)
          }
        }
        childrenArray.length == 0 ? 1 : itemObj.children = childrenArray
        itemArray.push(itemObj)
      }
      
      setMenuList(itemArray)
      var menuRightData = []
      menuRightData.push(...rtdata.yjcdList)
      menuRightData.push(...rtdata.ejcdList)
      menuRightData.sort((a, b) => a.cdpx - b.cdpx);
      setMenuRightList(menuRightData)
    } catch (error) {
      console.error('查询菜单失败:', error);
      if (error.message == '登录已过期') {
        openNotification_util('查询菜单失败，请稍后重试');
      }
    }
  }

  const updateMenuList = async (sfsc, cdqx, cdmc) => {
    try {
      await apiRequest("/admin/sys/updateMenuList", {
        method: 'POST',
        body: JSON.stringify({ 
          storage: {
            userid: storage.userid,
            ygbh: storage.ygbh
          },
          sfsc, 
          cdqx, 
          cdmc 
        })
      });
    } catch (error) {
      console.error('更新菜单失败:', error);
      throw error;
    }
  }

  const queryScList = async () => {
    try {
      let rtdata = await apiRequest("/admin/sys/queryScList", {
        method: 'POST',
        body: JSON.stringify({ 
          storage: {
            userid: storage.userid,
            ygbh: storage.ygbh
          }
        })
      });

      // 构建收藏菜单数组
      var favoriteMenus = []
      for (let item of rtdata) {
        let menuItem = {
          label: <div id={item.id}><Highlighter highlightStyle={{
            backgroundColor: 'yellow', padding: 0,
          }}
            searchWords={[searchText]} autoEscape textToHighlight={item.cdmc} /><div className="icon-button" style={{ position: 'absolute', right: '1vw', top: '0', zIndex: "10", width: '3vw', textAlign: 'center' }}
              onClick={e => { handleClick(item, e) }}><IconFont
                type={item.sfsc != '是' ? "shoucang" : "yellowStar"}></IconFont></div>
          </div>, key: item.cdmc, route: item.cdly, theme: 'light', id: item.id
        }
        favoriteMenus.push(menuItem)
      }

      // 更新menuList中首页的children
      setMenuList(prevMenuList => {
        const updatedMenuList = [...prevMenuList];
        const homeMenuIndex = updatedMenuList.findIndex(menu => menu.key === 'homepage');
        if (homeMenuIndex !== -1) {
          updatedMenuList[homeMenuIndex] = {
            ...updatedMenuList[homeMenuIndex],
            children: favoriteMenus
          };
        }
        return updatedMenuList;
      });

      // 保持原有的scList格式用于其他地方
      var itemArray = []
      var itemObj = { label: "收藏夹", key: '1', icon: <IconFont type="shoucang" />, theme: 'light' }
      itemObj.children = favoriteMenus.length === 0 ? [] : favoriteMenus
      itemArray.push(itemObj)
      setScLisst(itemArray)
    } catch (error) {
      console.error('查询收藏失败:', error);
      if (error.message !== '登录已过期') {
        openNotification_util('查询收藏失败，请稍后重试');
      }
    }
  }

  // 初始化检查登录状态和令牌
  const initializeAuth = async () => {
    try {
      // 检查基本登录信息
      if (!hasValidLoginData()) {
        forceLogout("登录信息不完整，请重新登录");
        return;
      }

      // 检查令牌状态
      const tokenValid = await checkTokenExpiration();
      if (!tokenValid) {
        return; // checkTokenExpiration 已处理跳转
      }

      console.log('登录状态验证成功');
    } catch (error) {
      console.error('初始化认证失败:', error);
      forceLogout("认证失败，请重新登录");
    }
  }

  // 处理一级菜单点击
  const handlePrimaryMenuClick = (menuItem) => {
    setSelectedPrimaryMenu(menuItem.cdmc);
    
    // 如果点击的是首页，直接跳转
    if (menuItem.cdmc === '首页') {
      setnowroute({ route: '/shipSRM/mainpage', title: '首页' });
    }
    
    // 找到对应的二级菜单
    const currentMenu = menuList.find(item => item.label === menuItem.cdmc);
    if (currentMenu && currentMenu.children) {
      setSecondaryMenuList(currentMenu.children);
    } else {
      setSecondaryMenuList([]);
    }
  }

  // 处理二级菜单点击（兼容菜单事件与折叠菜单手动触发）
  const handleSecondaryMenuClick = (menuInfo) => {
    if (!menuInfo) {
      return;
    }

    const route = menuInfo.item?.props?.route || menuInfo.route || menuInfo.path || '';
    const rawTitle = menuInfo.label ?? menuInfo.key ?? menuInfo.item?.props?.title;
    const title = typeof rawTitle === 'string'
      ? rawTitle
      : extractMenuLabel(rawTitle, menuInfo.key || route || '');

    if (!route) {
      console.warn('未能解析菜单路由，忽略该点击事件。', menuInfo);
      return;
    }

    const tabTitle = title || route;

    const exists = activetabs.some(tab => tab.key === route);
    if (!exists) {
      setActivetabs(prevTabs => [...prevTabs, {
        title: tabTitle,
        route: route,
        key: route
      }]);
      setnowroute({ route: route, title: tabTitle });
    }

    setnowActiveKey(route);
    tonormal(route);
  }


  
  // 用户菜单
  const userMenuItems = [
    {
      key: 'profile',
      label: '个人信息',
      icon: <UserOutlined />,
      onClick: () => {
        history.push('/shipSRM/userinfo');
      }
    },
    {
      key: 'changePassword',
      label: '修改密码',
      icon: <SettingOutlined />,
      onClick: () => {
        setIfxgmm(true);
      }
    },
    {
      type: 'divider'
    },
    {
      key: 'logout',
      label: '退出登录',
      icon: <IconFont type="lagout" />,
      onClick:()=>{
        handlelogout()
      }
    }
  ];

  //如果当前路由不在activetabs中,则跳转到首页 用 location去获取
  useEffect(() => {
    // 确保首页页签始终存在
    const tabsWithHome = ensureHomeTabExists(activetabs);
    if (tabsWithHome.length !== activetabs.length || 
        JSON.stringify(tabsWithHome) !== JSON.stringify(activetabs)) {
      setActivetabs(tabsWithHome);
    }
    
    if (!activetabs.some(tab => tab.route === location.pathname)) {
      if (storage['nowroute']) {
        setnowroute(JSON.parse(storage['nowroute']))
        console.log(JSON.parse(storage['nowroute']).route,"JSON.parse(storage['nowroute']).route");
        history.push(JSON.parse(storage['nowroute']).route)
      }
      else {
        setnowroute({ route: "/shipSRM/mainpage", title: "首页" })
      }
    }
  }, [])

  // 组件初始化时进行认证检查
  useEffect(() => {
    initializeAuth();
  }, []);

  // 初始化首页页签
  useEffect(() => {
    // 确保首页页签始终存在
    const tabsWithHome = ensureHomeTabExists([]);
    setActivetabs(tabsWithHome);
    
    // 如果没有当前活动的页签，设置首页为活动页签
    if (!nowactiveKey) {
      setnowActiveKey('/shipSRM/mainpage');
    }
  }, []);

  // 定期检查令牌状态（每5分钟检查一次）
  useEffect(() => {
    const tokenCheckInterval = setInterval(() => {
      checkTokenExpiration();
    }, 5 * 60 * 1000); // 5分钟

    return () => clearInterval(tokenCheckInterval);
  }, []);

  useEffect(() => {
    // 延迟加载菜单，确保认证完成
    const loadMenus = async () => {
      if (hasValidLoginData() && getToken()) {
        await queryMenuList();
        // 总是加载收藏列表，确保首页收藏菜单正确显示
        await queryScList();
      }
    };

    const timer = setTimeout(loadMenus, 100);
    return () => clearTimeout(timer);
  }, [searchText, needrefreshsclist]);

  // 更新当前选中的一级菜单对应的二级菜单
  useEffect(() => {
    if (selectedPrimaryMenu && menuList.length > 0) {
      const currentMenu = menuList.find(item => item.label === selectedPrimaryMenu);
      if (currentMenu && currentMenu.children) {
        setSecondaryMenuList(currentMenu.children);
      } else {
        setSecondaryMenuList([]);
      }
    }
  }, [selectedPrimaryMenu, menuList]);

  useEffect(() => {
    // 检查用户是否已登录
    if(!hasValidLoginData()){
      console.log("没有完整的登录信息");
      forceLogout("登录信息缺失，请重新登录");
      return;
    }

    //去掉#/shipSRM/gyszx/gyslb前面的#
    let hash = location.hash.replace('#', '')
    // console.log('hash',location.pathname,menuList)
    //如果hash不在menuList中，并且hash不等于/shipSRM/mainpage，则设置为404
    if(location.pathname.includes('form') || menuList.length == 0) return
    
    // 检查当前路径是否在路由配置中
    const routeConfig = getRouteConfig(location.pathname);
    if (!routeConfig || !routeConfig.inMainLayout) {
      // 如果路由配置不存在或不在主布局中，检查菜单权限
      let flag = false
      for(let item of menuList){
        if(item.route == location.pathname){
          flag = true
        }
        if(item.children){
          for(let item2 of item.children){
            if(item2.route == location.pathname){
              flag = true
            }
          }
        }
      }
      //设置为404
      if(!flag){
        history.push('/shipSRM/404')
      }
    }
  }, [location]);

  const tonormal = (route, type) => {
    console.log(route,"route");
    history.push(route)
  }

  useEffect(() => {
    if (!nowroute) return;

    let newActivetabs = [...activetabs];

    // 检查路由是否已存在于tabs中
    const existingTab = activetabs.find(tab => tab.route === nowroute.route);

    if (existingTab) {
      // 路由已存在,检查title是否一致
      if (existingTab.title !== nowroute.title && nowroute.title) {
        openNotification_util(`请先关闭已打开的"${existingTab.title}"页面`);
        setnowActiveKey(existingTab.key);
        return;
      }
      else{
        // 激活对应tab
        setnowActiveKey(existingTab.key);
        console.log(nowroute.route,"nowroute.route");
        history.push(nowroute.route);
      }
      
    } else {
      // 路由不存在,需要新建tab
      // if (activetabs.length >= 10) {
      //   openNotification_util("多开页签已达上限");
      //   return;
      // }

      // 从菜单中查找路由信息，或者使用默认信息
      const menuItem = menuRightList.find(menu => menu.cdly === nowroute.route) || {
        cdly: nowroute.route,
        cdmc: nowroute.title || (nowroute.route === '/shipSRM/mainpage' ? '首页' : '未知页面')
      };

      // 创建新tab，首页不可关闭
      const newTab = {
        key: menuItem.cdly,
        title: menuItem.cdmc,
        route: menuItem.cdly,
        closable: menuItem.cdly !== '/shipSRM/mainpage'
      };
      console.log(newTab, "newTab");
      newActivetabs.push(newTab);
      
      // 确保首页页签在第一个位置
      newActivetabs = ensureHomeTabExists(newActivetabs);
      
      setnowActiveKey(menuItem.cdly);
      console.log(nowroute.route,"nowroute.route");
      history.push(nowroute.route);
    }

    // 处理需要关闭的路由
    if (nowroute.closeroute) {
      newActivetabs = newActivetabs.filter(tab => tab.route !== nowroute.closeroute);
    }

    setActivetabs(newActivetabs);

  }, [nowroute]);

  const handleOpenChange = (openKeys) => {
    setOpenKeys(openKeys);
  };

  const handlelogout = async () => {
    try {
      // 调用后端登出接口
      const token = getToken();
      if (token) {
        await fetch("/admin/sys/logout", {
          method: 'POST',
          mode: 'cors',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
          }
        });
      }
    } catch (error) {
      console.error('登出接口调用失败:', error);
    } finally {
      // 无论接口是否成功，都清除本地数据并跳转
      forceLogout("已成功登出");
    }
  }

  const handletomainpage = () => {
    history.push({ pathname: '/shipSRM/mainpage' });
  }
  const handleuserinfo = () => {
    history.push({ pathname: '/shipSRM/userinfo' });
  }

  const toggleCollapsed = () => {
    setcollapsed(!collapsed);
  };

  const handleSearch = (value) => {
    setSearchText(value)
    if (value != '') {
      const result = secondaryMenuList.filter(item =>
        item.key.includes(value)
      );
      // 可以根据搜索结果进行特殊处理
    }
  }

  // 页面样式修复功能
  useEffect(() => {
    const fixPageStyles = () => {
      // 获取主内容区域的样式信息
      const mainPageContent = document.querySelector('.mainpage-page-content');
      if (!mainPageContent) return;

      const mainContentStyles = window.getComputedStyle(mainPageContent);
      
      // 查找所有可能需要修复的页面容器
      const pageContainers = document.querySelectorAll('.mainpage-page-content > div');
      
      pageContainers.forEach(container => {
        const style = window.getComputedStyle(container);
        
        // 统一页面容器样式，确保与 mainpage-page-content 一致
        container.style.position = 'relative';
        container.style.top = 'auto';
        container.style.left = 'auto';
        container.style.right = 'auto';
        container.style.bottom = 'auto';
        container.style.height = '100%';
        container.style.width = '100%';
        container.style.overflow = 'auto';
        container.style.padding = '14px';
        container.style.boxSizing = 'border-box';
        container.style.backgroundColor = '#f5f5f5';
        container.style.minHeight = '100%';
        
        // 添加统一的类名，便于样式管理
        if (!container.classList.contains('page-content-unified')) {
          container.classList.add('page-content-unified');
        }
        
        // 检查是否为表单页面，如果是则不进行强制宽度修复
        const isFormPage = container.querySelector('[data-page-type="form"]') ||
                          container.querySelector('.ant-form') ||
                          window.location.pathname.includes('form') ||
                          container.closest('[data-page-type="form"]');
        
        if (isFormPage) {
          // 表单页面特殊处理
          container.style.overflow = 'hidden';
          
          // 确保表单页面内部容器正确设置
          const innerContainer = container.querySelector('div[style*="width: 100%"]');
          if (innerContainer) {
            innerContainer.style.width = '100%';
            innerContainer.style.height = '100%';
            innerContainer.style.overflow = 'auto';
            innerContainer.style.boxSizing = 'border-box';
          }
        } else {
          // 修复内部表格容器
          const tableWrappers = container.querySelectorAll('.ant-table-wrapper');
          tableWrappers.forEach(wrapper => {
            wrapper.style.width = '100%';
            wrapper.style.maxWidth = '100%';
          });

          // 修复内部表格
          const tables = container.querySelectorAll('.ant-table');
          tables.forEach(table => {
            table.style.width = '100%';
            table.style.maxWidth = '100%';
          });

          // 修复内部表单容器（仅在非表单页面）
          const formWrappers = container.querySelectorAll('.ant-form');
          formWrappers.forEach(form => {
            form.style.width = '100%';
            form.style.maxWidth = '100%';
          });

          // 修复内部卡片容器
          const cardWrappers = container.querySelectorAll('.ant-card');
          cardWrappers.forEach(card => {
            card.style.width = '100%';
            card.style.maxWidth = '100%';
          });

          // 修复固定宽度的容器（仅在非表单页面）
          const fixedWidthElements = container.querySelectorAll('div[style*="width"]');
          fixedWidthElements.forEach(element => {
            const elementStyle = window.getComputedStyle(element);
            if (elementStyle.width && elementStyle.width.includes('px') && parseInt(elementStyle.width) > 1200) {
              element.style.width = '100%';
              element.style.maxWidth = '100%';
            }
          });
        }

        // 修复明细容器样式
        const detailContainers = document.querySelectorAll('[data-detail-container]');
        detailContainers.forEach(container => {
          // 确保明细容器不会溢出
          container.style.boxSizing = 'border-box';
          container.style.maxWidth = '100%';
          
          // 根据容器类型设置不同的样式
          const containerType = container.getAttribute('data-detail-container');
          
          if (['gys_ghmx', 'gys_zzmx', 'gys_kpmx'].includes(containerType)) {
            // 供应商表单明细容器
            container.style.width = '98%';
            container.style.maxWidth = '98%';
            container.style.overflow = 'visible';
          } else if (['gyspj_form', 'gysbg_form'].includes(containerType)) {
            // 供应商表单主容器
            container.style.width = '98%';
            container.style.maxWidth = '98%';
            container.style.overflow = 'visible';
          }
          
          // 修复明细容器内的表格
          const tables = container.querySelectorAll('.ant-table-wrapper');
          tables.forEach(table => {
            table.style.width = '100%';
            table.style.maxWidth = '100%';
            table.style.overflowX = 'auto';
          });
          
          const tableElements = container.querySelectorAll('.ant-table');
          tableElements.forEach(table => {
            table.style.width = '100%';
            table.style.maxWidth = '100%';
            table.style.tableLayout = 'auto';
          });
        });
      });
    };

    // 响应式适配功能
    const handleResize = () => {
      // 获取当前视口信息
      const viewportWidth = window.innerWidth;
      const viewportHeight = window.innerHeight;
      const devicePixelRatio = window.devicePixelRatio || 1;
      
      // 根据屏幕尺寸调整页面缩放
      const mainPageContent = document.querySelector('.mainpage-page-content');
      if (mainPageContent) {
        // 设置CSS自定义属性，供其他组件使用
        document.documentElement.style.setProperty('--viewport-width', `${viewportWidth}px`);
        document.documentElement.style.setProperty('--viewport-height', `${viewportHeight}px`);
        document.documentElement.style.setProperty('--device-pixel-ratio', devicePixelRatio.toString());
        
        // 为小屏幕设备调整字体大小
        if (viewportWidth < 1366) {
          document.documentElement.style.setProperty('--base-font-size', '12px');
        } else if (viewportWidth < 1920) {
          document.documentElement.style.setProperty('--base-font-size', '14px');
        } else {
          document.documentElement.style.setProperty('--base-font-size', '14px');
        }
      }
      
      // 重新执行样式修复
      setTimeout(fixPageStyles, 100);
    };

    // 页面加载后执行修复
    const timer = setTimeout(fixPageStyles, 100);
    
    // 路由变化后也执行修复
    const interval = setInterval(fixPageStyles, 500);

    // 监听窗口大小变化
    window.addEventListener('resize', handleResize);
    
    // 初始执行一次响应式适配
    handleResize();

    return () => {
      clearTimeout(timer);
      clearInterval(interval);
      window.removeEventListener('resize', handleResize);
    };
  }, [location.pathname]);

  // 添加全局样式注入功能
  useEffect(() => {
    const injectGlobalStyles = () => {
      // 检查是否已经注入过样式
      if (document.getElementById('mainpage-global-styles')) return;

      const style = document.createElement('style');
      style.id = 'mainpage-global-styles';
      style.textContent = `
        /* 页面容器统一样式 */
        .page-content-unified {
          position: relative !important;
          top: auto !important;
          left: auto !important;
          right: auto !important;
          bottom: auto !important;
          height: 100% !important;
          width: 100% !important;
          overflow: auto !important;
          padding: 14px !important;
          box-sizing: border-box !important;
          background-color: #f5f5f5 !important;
          min-height: 100% !important;
        }

        /* 响应式字体大小 */
        .page-content-unified * {
          font-size: var(--base-font-size, 14px) !important;
        }

        /* 表格响应式 - 仅在非表单页面 */
        .page-content-unified:not([data-page-type="form"]) .ant-table-wrapper {
          width: 100% !important;
          max-width: 100% !important;
          overflow-x: auto !important;
        }

        .page-content-unified:not([data-page-type="form"]) .ant-table {
          width: 100% !important;
          max-width: 100% !important;
          min-width: 800px !important;
        }

        /* 表单响应式 - 仅在非表单页面 */
        .page-content-unified:not([data-page-type="form"]) .ant-form {
          width: 100% !important;
          max-width: 100% !important;
        }

        /* 卡片响应式 - 仅在非表单页面 */
        .page-content-unified:not([data-page-type="form"]) .ant-card {
          width: 100% !important;
          max-width: 100% !important;
        }

        /* 按钮组响应式 */
        .page-content-unified .ant-btn-group {
          flex-wrap: wrap !important;
        }

        /* 输入框响应式 */
        .page-content-unified .ant-input,
        .page-content-unified .ant-select {
          max-width: 100% !important;
        }

        /* 小屏幕适配 */
        @media (max-width: 1366px) {
          .page-content-unified {
            padding: 12px !important;
          }
          
          .page-content-unified .ant-table {
            font-size: 12px !important;
          }
          
          .page-content-unified .ant-btn {
            font-size: 12px !important;
            padding: 4px 8px !important;
          }
        }

        /* 超大屏幕适配 */
        @media (min-width: 2560px) {
          .page-content-unified {
            padding: 24px !important;
          }
          
          .page-content-unified * {
            font-size: 14px !important;
          }
        }

        /* 高DPI屏幕适配 */
        @media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) {
          .page-content-unified {
            -webkit-font-smoothing: antialiased !important;
            -moz-osx-font-smoothing: grayscale !important;
          }
        }

        /* 表单页面特殊样式 */
        .page-content-unified[data-page-type="form"] {
          overflow: hidden !important;
        }

        /* 表单页面内部容器样式 */
        .page-content-unified[data-page-type="form"] > div:first-child {
          width: 100% !important;
          height: 100% !important;
          overflow: auto !important;
          box-sizing: border-box !important;
        }

        .page-content-unified[data-page-type="form"] .ant-form {
          width: auto !important;
          max-width: none !important;
        }

        .page-content-unified[data-page-type="form"] .ant-table-wrapper {
          width: auto !important;
          max-width: none !important;
        }

        .page-content-unified[data-page-type="form"] .ant-card {
          width: auto !important;
          max-width: none !important;
        }

        /* 明细容器样式优化 */
        [data-detail-container] {
          box-sizing: border-box !important;
          max-width: 100% !important;
        }

        /* 供应商表单明细容器特殊处理 */
        [data-detail-container="gys_ghmx"],
        [data-detail-container="gys_zzmx"],
        [data-detail-container="gys_kpmx"] {
          width: 100% !important;
          max-width: 100% !important;
          overflow-x: auto !important;
          overflow-y: visible !important;
          margin-bottom: 1rem !important;
          box-sizing: border-box !important;
        }

        /* 供应商表单主容器 */
        [data-detail-container="gyspj_form"],
        [data-detail-container="gysbg_form"] {
          width: 98% !important;
          max-width: 98% !important;
          overflow: visible !important;
          box-sizing: border-box !important;
        }

        /* 明细容器内的表格优化 */
        [data-detail-container] .ant-table-wrapper {
          width: 100% !important;
          max-width: 100% !important;
          overflow-x: auto !important;
        }

        [data-detail-container] .ant-table {
          width: 100% !important;
          max-width: 100% !important;
          table-layout: auto !important;
        }

        /* 防止明细容器溢出父容器 */
        [data-detail-container] * {
          max-width: 100% !important;
          box-sizing: border-box !important;
        }
      `;
      
      document.head.appendChild(style);
    };

    injectGlobalStyles();

    return () => {
      // 清理全局样式
      const style = document.getElementById('mainpage-global-styles');
      if (style) {
        style.remove();
      }
    };
  }, []);

  // 如果正在检查令牌，显示加载状态
  if (tokenChecking && !hasValidLoginData()) {
    return (
      <div style={{ 
        height: '100vh', 
        width: '100%', 
        display: 'flex', 
        justifyContent: 'center', 
        alignItems: 'center',
        backgroundColor: '#f0f0f0'
      }}>
        <div style={{ textAlign: 'center' }}>
          <div style={{ fontSize: '14px', marginBottom: '10px' }}>正在验证登录状态...</div>
          <div>请稍候</div>
        </div>
      </div>
    );
  }

  return (
    <div style={{ height: '100vh', width: '100%', display: 'flex', flexDirection: 'column' }}>
      {/* 顶部导航栏 - 重新设计统一布局 */}
      <div className="mainpage-header-unified">
        {/* 左侧 Logo */}
        <div className="mainpage-logo">
          <img src={logo} alt="logo" />
          
        </div>

        {/* 中间一级菜单区域 */}
        <div className="mainpage-primary-menu-container">
          <div className="mainpage-primary-menu-scroll">
            {primaryMenuList.map(item => {
              const isSelected = selectedPrimaryMenu === item.cdmc;
              return (
                <div
                  key={item.cdmc}
                  className={`mainpage-primary-menu-item${isSelected ? ' selected' : ''}`}
                  onClick={() => handlePrimaryMenuClick(item)}
                  title={item.label}
                >
                  <div className="menu-icon" style={{color: isSelected ? '#a90f14' : '#666666'}}>
                    {item.icon}
                  </div>
                  <div className="menu-label" style={{fontSize: '14px', color: isSelected ? '#a90f14' : '#666666'}}>
                    {item.label}
                  </div>
                  {/* 选中状态的底部指示器 */}
                  {isSelected && <div className="menu-indicator" />}
                </div>
              );
            })}
          </div>
        </div>

        {/* 右侧用户信息区域 */}
        <div className="mainpage-user-area">
          {/* 消息通知 */}
          <Badge count={notificationCount} size="small">
            <Button 
              type="text" 
              icon={<BellOutlined />} 
              className="notification-btn"
              onClick={() => {
                console.log('消息通知点击');
              }}
            />
          </Badge>

          {/* 用户信息下拉菜单 */}
          <Dropdown menu={{ items: userMenuItems }} placement="bottomRight">
            <Space className="user-info">
              <Avatar size="small" icon={<UserOutlined />} />
              <span>{storage.ygxm}</span>
            </Space>
          </Dropdown>
        </div>
      </div>



      {/* 主体内容区域 */}
      <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
        {/* 左侧二级菜单栏 */}
        <div className={`mainpage-sidebar ${collapsed ? 'collapsed' : ''}`}>
          {/* 菜单收起按钮和搜索框 */}
          <div className="mainpage-sidebar-header">
            <Button 
              type="text" 
              icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
              onClick={toggleCollapsed}
              style={{ minWidth: '32px' }}
            />
            {!collapsed && (
              <Search 
                placeholder="搜索菜单" 
                onSearch={handleSearch}
                style={{ flex: 1 }}
                size="small"
              />
            )}
          </div>

          {/* 折叠状态下的下拉菜单按钮 */}
          {collapsed && (
            <div className="mainpage-sidebar-collapsed-menu">
              <Dropdown 
                menu={{ 
                  items: secondaryMenuList
                    .map(item => sanitizeMenuItemForDropdown(item))
                    .filter(Boolean),
                  onClick: ({ key }) => {
                    // 查找对应的菜单项并触发点击
                    const findAndClickMenuItem = (items, targetKey) => {
                      for (let item of items) {
                        if (String(item.key) === String(targetKey)) {
                          handleSecondaryMenuClick({
                            key: String(item.key || ''),
                            route: item.route,
                            label: extractMenuLabel(item.label, String(item.key || ''))
                          });
                          return true;
                        }
                        if (item.children) {
                          if (findAndClickMenuItem(item.children, targetKey)) {
                            return true;
                          }
                        }
                      }
                      return false;
                    };
                    findAndClickMenuItem(secondaryMenuList, key);
                  }
                }} 
                placement="bottomLeft"
                trigger={['click']}
              >
                <Button 
                  type="text" 
                  style={{ 
                    width: '100%', 
                    height: '40px', 
                    display: 'flex', 
                    alignItems: 'center', 
                    justifyContent: 'space-between',
                    border: '1px solid #d9d9d9',
                    borderRadius: '6px',
                    margin: '8px',
                    backgroundColor: '#fafafa',
                    padding: '0 12px'
                  }}
                  title={`${selectedPrimaryMenu || '菜单'} - 点击展开子菜单`}
                >
                  <div style={{ 
                    display: 'flex', 
                    alignItems: 'center', 
                    flex: 1,
                    overflow: 'hidden'
                  }}>
                    <MenuOutlined style={{ fontSize: '12px', color: '#666', marginRight: '6px' }} />
                    <span style={{ 
                      fontSize: '12px', 
                      color: '#666', 
                      overflow: 'hidden',
                      textOverflow: 'ellipsis',
                      whiteSpace: 'nowrap',
                      textAlign: 'left'
                    }}>
                      {selectedPrimaryMenu || '菜单'}
                    </span>
                  </div>
                  <DownOutlined style={{ fontSize: '10px', color: '#999', marginLeft: '4px' }} />
                </Button>
              </Dropdown>
            </div>
          )}

          {/* 展开状态下的二级菜单列表 */}
          {!collapsed && (
            <div className="mainpage-sidebar-content">
              <Menu
                mode="inline"
                theme="light"
                openKeys={openKeys}
                onOpenChange={handleOpenChange}
                onClick={handleSecondaryMenuClick}
                items={secondaryMenuList}
                style={{ border: 'none', height: '100%' }}
              />
            </div>
          )}
        </div>

        {/* 右侧内容区域 */}
        <div className="mainpage-content">
          {/* 标签页导航 */}
          {activetabs.length > 0 && (
            <div className="mainpage-tabs-container">
              <Tabs
                className='mainpage-tabs'
                activeKey={nowactiveKey}
                onChange={(activeKey) => {
                  setnowActiveKey(activeKey)
                  let title = activetabs.find(tab => tab.key === activeKey).title
                  let route = activetabs.find(tab => tab.key === activeKey).route
                  setnowroute({ route: route, title: title })
                }}
                items={activetabs.map(tab => ({
                  label: (
                    <div 
                      onMouseEnter={() => setnowtabkey(tab.key)}
                      onContextMenu={handleContextMenu}
                    >
                      {tab.title}
                    </div>
                  ),
                  key: tab.key,
                  children: null,
                  closable: tab.route !== '/shipSRM/mainpage' // 首页页签不可关闭
                }))}
                onEdit={(targetKey, action) => {
                  setOpenKeys([])
                  if (action === 'remove') {
                    // 防止关闭首页页签
                    if (targetKey === '/shipSRM/mainpage') {
                      openNotification_util("首页页签不能关闭");
                      return;
                    }
                    
                    let cacheKey = targetKey.split('/').pop();
                    dropByCacheKey(cacheKey)
                    const newActivetabs = activetabs.filter(tab => tab.key !== targetKey);
                    
                    // 确保首页页签始终存在
                    const finalTabs = ensureHomeTabExists(newActivetabs);
                    setActivetabs(finalTabs);
                    
                    if (finalTabs.length === 1) {
                      // 如果只剩首页页签，激活首页
                      setnowActiveKey('/shipSRM/mainpage')
                      tonormal('/shipSRM/mainpage')
                    } else {
                      // 激活首页页签（因为首页始终在第一个位置）
                      setnowActiveKey('/shipSRM/mainpage')
                      tonormal('/shipSRM/mainpage')
                    }
                  }
                }}
                type="editable-card"
                hideAdd={true}
                size="small"
              />
            </div>
          )}

          {/* 页面内容区域 */}
          <div className="mainpage-page-content">
            {/* 这里将显示具体的页面内容 */}
            {activetabs.length > 0 && nowactiveKey ? (
              <DynamicComponentLoader path={nowactiveKey} />
            ) : (
              <div style={{ 
                height: '100%', 
                display: 'flex', 
                justifyContent: 'center', 
                alignItems: 'center',
                color: '#999',
                fontSize: '14px'
              }}>
                请选择菜单项目以开始使用
              </div>
            )}
          </div>
        </div>
      </div>

      {/* 修改密码弹窗 */}
      <Modal 
        open={ifxgmm} 
        style={{ top: "5vh", backgroundColor: "rgba(0,0,0,0.8)" }} 
        onCancel={() => setIfxgmm(false)}
        width="20vw"
        okButtonProps={{ style: { display: "none" } }} 
        cancelButtonProps={{ style: { display: "none" } }}
        destroyOnClose={true}
        bodyStyle={{ borderRadius: "8px", boxShadow: "0 8px 32px rgba(0,0,0,0.3)" }}
      >
        <Userinfo 
          hiddenbutton={true} 
          transfer={true}
          onCancel={() => setIfxgmm(false)}
          setIfxgmm={setIfxgmm}
        />
      </Modal>

      {/* 右键菜单 */}
      <RightMenu id={MENU_ID} style={{zIndex: 1052}}>
        <Item onClick={handleCloseAll}>关闭全部</Item>
        <Item onClick={handleCloseOther}>关闭其他</Item>
        <Item onClick={handleCloseRight}>关闭右侧</Item>
      </RightMenu>
    </div>
  );
}

export default Mainpage

